<template>
  <div>
    <page-list :x-uri="uri" :doactions="doactions" :custom-components="custom" :tree="true">
      <!-- 自定义tab -->
      <template v-slot:page-tabs>
        <tabs :tabs="tabs" />
      </template>
      <!-- 页面操作按钮 -->
      <template v-slot:page-button>
        <el-button v-auth="'exam.module.config'" size="mini" type="primary" @click="create">新建专项</el-button>
      </template>
    </page-list>
    <el-dialog :title="dialogTitle" :visible.sync="dialogVisible" width="600px" :close-on-click-modal="false" top="30vh">
      <el-form v-if="dialogVisible" ref="special" :model="special" label-width="100px">
        <el-form-item v-if="parentTitle" size="small" label="所属专项">{{ parentTitle }}</el-form-item>
        <el-form-item v-if="cateVisible" :rules="rulesCate" label="分类">
          <el-cascader v-model="cateValue" :options="category" :props="{ expandTrigger: 'hover' }" @change="handleChange" />
        </el-form-item>
        <el-form-item prop="title" :rules="rulesTitle" size="small" label="专项名称">
          <edu-input key="title" :value.sync="special.title" :args="{ minlength: 2, maxlength: 30 }" />
        </el-form-item>
        <el-form-item v-if="visiblePriceField" prop="price" size="small" label="专项价格">
          <edu-input-number key="price" :value.sync="special.price" :args="{ min: 0, precision: 2 }" />
        </el-form-item>
        <el-form-item v-if="visiblePriceField" prop="credit_redeem" size="small" label="积分抵扣">
          <el-switch v-model="special.credit_redeem" :active-value="1" :inactive-value="0" />
        </el-form-item>
        <el-form-item v-if="visiblePriceField && special.credit_redeem === 1" prop="credit_redeem_percent" size="small" label="最高抵扣比例">
          <edu-input-number key="credit_redeem_percent" :value.sync="special.credit_redeem_percent" :args="{ min: 0, max: 100 }" />
          <div class="edu-tips">可抵扣订单金额的百分比</div>
        </el-form-item>
        <el-form-item size="small">
          <el-row type="flex" justify="end">
            <el-button type="primary" :disabled="disableSubmit" @click="onSubmit">保存</el-button>
            <el-button @click="dialogVisible = false">关闭</el-button>
          </el-row>
        </el-form-item>
      </el-form>
    </el-dialog>
  </div>
</template>

<script>
import PageList from '@public/template/page_list.vue';
import EduInput from '@public/form/input.vue';
import EduInputNumber from '@public/form/input_number.vue';
import Tabs from '../tabs';
import SpecialStatus from './components/special_status.vue';
import SpecialPrice from './components/special_price.vue';
import Redeem from './components/special_credit_redeem.vue';
export default {
  components: {
    PageList,
    EduInput,
    EduInputNumber,
    Tabs
  },
  inject: ['reload'],
  data() {
    return {
      uri: '/exam/admin/module/' + this.$route.params.id + '/special/config',
      tabs: [
        {
          title: '专项配置',
          uri: '/exam/module/' + this.$route.params.id + '/special/config',
          meta: {
            permission: 'exam.module.config'
          }
        }
      ],
      doactions: [
        {
          title: '添加子专项',
          meta: { permission: 'exam.module.config' },
          display: ({ row }) => {
            return row.level < 2 && row.topic_count == 0;
          },
          callback: this.addChildren
        },
        {
          title: '专项试题',
          meta: { permission: 'exam.module.config' },
          display: ({ row }) => {
            return !row.children;
          },
          callback: this.topicList
        },
        { title: '编辑', meta: { permission: 'exam.module.config' }, callback: this.edit },
        { title: '删除', meta: { permission: 'exam.module.config' }, callback: this.delete }
      ],
      dialogVisible: false,
      cateVisible: false,
      category: [],
      cateValue: [],
      disableSubmit: false,
      special: {
        pid: 0,
        title: '',
        credit_redeem: 0
      },
      rulesCate: [{ required: true }],
      rulesTitle: [
        { required: true, message: '专项名称必须填写', trigger: ['blur', 'change'] },
        {
          pattern: /^.{1,50}$/,
          message: '专项名称为1-50个字符',
          trigger: ['blur', 'change']
        }
      ],
      dialogTitle: '新建专项',
      parentTitle: '',
      visiblePriceField: true,
      custom: {
        status: SpecialStatus,
        credit_redeem: Redeem,
        price: SpecialPrice
      }
    };
  },
  created() {
    this.loadCate();
  },
  methods: {
    loadCate: function() {
      var uri = '/exam/admin/category/tree';
      this.$http.send(
        'GET',
        uri,
        {},
        res => {
          this.category = res.data;
        },
        err => {
          this.$message.error(err.msg);
        },
        false
      );
    },
    handleChange: function(value) {
      this.cateValue = value;
      this.special.category = value;
    },
    // 新建顶级专项
    create: function() {
      this.dialogTitle = '新建专项'
      this.special = {
        pid: 0,
        title: '',
        price: 0,
        category: []
      };
      this.dialogVisible = true;
      // 显示分类
      this.cateVisible = true;
      this.visiblePriceField = true;
      this.parentTitle = '';
    },
    // 添加子专项
    addChildren: function({ row }) {
      this.dialogTitle = '新建专项'
      this.special = {
        pid: row.id,
        title: ''
      };
      this.dialogVisible = true;
      // 不显示分类
      this.cateVisible = false;
      this.parentTitle = row.title;
      this.visiblePriceField = false;
    },
    // 编辑
    edit: function({ row }) {
      this.dialogTitle = '编辑专项'
      this.special = {
        id: row.id,
        title: row.title,
        credit_redeem: row.credit_redeem
      };
      this.dialogVisible = true;
      if (row.pid == 0) {
        this.visiblePriceField = true;
        this.parentTitle = '';
        this.special.price = row.price;
        this.special.credit_redeem = row.credit_redeem;
        this.special.credit_redeem_percent = row.credit_redeem_percent;
        this.cateValue = row.fullcategorypath;
        this.special.category = this.cateValue;
      } else {
        this.visiblePriceField = false;
      }
      this.cateVisible = !!(row.level == 1 && row.topic_count == 0);
    },
    // 专项试题
    topicList: function({ row }) {
      this.$router.push({
        path: '/exam/module/' + this.$route.params.id + '/special/' + row.id + '/topic'
      });
    },
    // 保存
    onSubmit: function() {
      if (this.special.category && !this.special.category.length) {
        this.$message.error('请选择分类');
      } else {
        this.$refs['special'].validate(valid => {
          if (valid) {
            this.disableSubmit = true;
            var method = 'POST';
            var uri = '/exam/admin/module/' + this.$route.params.id + '/special/create';

            if (this.special.id) {
              method = 'PUT';
              uri = '/exam/admin/module/' + this.$route.params.id + '/special/' + this.special.id + '/edit';
            }
            this.$http.send(
              method,
              uri,
              this.special,
              response => {
                this.$message.success(response.msg, _ => {
                  this.reload();
                });
              },
              error => {
                this.disableSubmit = false;
                this.$message.error(error.msg);
              },
              false
            );
          }
        });
      }
    },
    // 删除
    delete: function({ row }) {
      this.$box
        .confirm('确认删除吗')
        .then(() => {
          this.$http.delete(
            '/exam/admin/module/' + this.$route.params.id + '/special/' + row.id + '/delete',
            {},
            response => {
              this.$message.success(response.msg, _ => {
                this.reload();
              });
            },
            error => {
              this.$message.error(error.msg);
            }
          );
        })
        .catch(() => {});
    }
    // ,
    // change: function(value) {
    //   this.disabled = true;
    //   this.$http.put(
    //     '/exam/admin/module/' + this.row.module_id + '/special/' + this.row.id + '/edit/credit_redeem',
    //     { credit_redeem: value },
    //     response => {
    //       this.disabled = false;
    //     },
    //     error => {
    //       this.$message.error(error.msg);
    //     },
    //     false
    //   );
    // }
  }
};
</script>
